package servlets;

import java.io.IOException;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.web.context.support.WebApplicationContextUtils;

import domain.Contact;
import domain.ContactGroup;
import domain.Entreprise;
import domain.PhoneNumber;
import dao.DAOContact;
import dao.DAOGroup;

/**
 * Servlet implementation class EditContactServlet
 */
public class EditContactServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;
	private Contact theContact;

	/**
	 * @see HttpServlet#HttpServlet()
	 */
	public EditContactServlet() {
		super();
		// TODO Auto-generated constructor stub
	}

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse
	 *      response)
	 */
	protected void doGet(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		// doGetOrPost(request, response);
		try {

			org.springframework.context.ApplicationContext context = WebApplicationContextUtils
					.getWebApplicationContext(getServletContext());
			DAOContact dao = (DAOContact) context.getBean("contactDAO");

			int id = Integer.parseInt(request.getParameter("id"));
			Contact c = dao.searchById(id);
			theContact = c;
			if (c != null) {
				System.out.println(c.getLastName());
				request.setAttribute("contact", c);
				RequestDispatcher dispatcher = request
						.getRequestDispatcher("pages/updateContact.jsp");
				dispatcher.forward(request, response);
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse
	 *      response)
	 */
	protected void doPost(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		String firstName = request.getParameter("firstname");
		String lastName = request.getParameter("lastname");
		String email = request.getParameter("email");
		String street = request.getParameter("street");
		String city = request.getParameter("city");
		String zip = request.getParameter("zip");
		// String country = request.getParameter("country");
		String phone1 = request.getParameter("phone1");
		String phone2 = request.getParameter("phone2");
		String phone3 = request.getParameter("phone3");
		String phonetype1 = request.getParameter("phonetype1");
		String phonetype2 = request.getParameter("phonetype2");
		String phonetype3 = request.getParameter("phonetype3");

		String g1 = request.getParameter("friendChk");
		String g2 = request.getParameter("familyChk");
		String g3 = request.getParameter("colleagueChk");
		String gOther = request.getParameter("other");

		theContact.setFirstName(firstName);
		theContact.setLastName(lastName);
		theContact.setEmail(email);
		theContact.getAddress().setStreet(street);
		theContact.getAddress().setCity(city);
		theContact.getAddress().setZip(zip);

		// update phone1
		((PhoneNumber) theContact.getPhones().toArray()[0])
				.setPhoneNumber(phone1);
		((PhoneNumber) theContact.getPhones().toArray()[0])
				.setPhoneKind(phonetype1);

		// update phone2
		if (!phone2.equals(""))
			if (theContact.getPhones().toArray().length > 1
					&& ((PhoneNumber) theContact.getPhones().toArray()[1])
							.getPhoneNumber() != phone2)
				((PhoneNumber) theContact.getPhones().toArray()[1])
						.setPhoneNumber(phone2);
			else
				theContact.getPhones().add(
						new PhoneNumber(phonetype2, phone2, theContact));
		else {
			if (theContact.getPhones().toArray().length > 1)
				theContact.getPhones().remove(
						(PhoneNumber) theContact.getPhones().toArray()[1]);
		}

		// update phone3
		if (!phone3.equals(""))
			if (theContact.getPhones().toArray().length > 2
					&& ((PhoneNumber) theContact.getPhones().toArray()[2])
							.getPhoneNumber() != phone3)
				((PhoneNumber) theContact.getPhones().toArray()[2])
						.setPhoneNumber(phone3);
			else
				theContact.getPhones().add(
						new PhoneNumber(phonetype3, phone3, theContact));
		else {
			if (theContact.getPhones().toArray().length > 2)
				theContact.getPhones().remove(
						(PhoneNumber) theContact.getPhones().toArray()[2]);
		}

		// update siret
		if (theContact instanceof Entreprise) {
			String siret = request.getParameter("siret");
			((Entreprise) theContact).setNumSiret(Integer.parseInt(siret));
		}

		// update group
		org.springframework.context.ApplicationContext context = WebApplicationContextUtils
				.getWebApplicationContext(getServletContext());
		DAOContact dao = (DAOContact) context.getBean("contactDAO");

		// DAOGroup daoGroup = (DAOGroup) context.getBean("daoGroup");
		// List<String> groupName = daoGroup.search();
		// Set<ContactGroup> grps = new HashSet<ContactGroup>();
		// boolean hasFriend = false;
		// boolean hasFamily = false;
		// boolean hasColleague = false;
		// for (ContactGroup g : theContact.getBooks()) {
		// if (g.getGroupName().equals(g1))
		// hasFriend = true;
		// if (g.getGroupName().equals(g2))
		// hasFamily = true;
		// if (g.getGroupName().equals(g3))
		// hasColleague = true;
		// }
		//
		// if (g1 != null && !hasFriend) {
		// ContactGroup grp = new ContactGroup();
		// grp.setGroupName(g1);
		// grps.add(grp);
		// }
		// if (g2 != null && !hasFamily) {
		// ContactGroup grp = new ContactGroup();
		// grp.setGroupName(g2);
		// grps.add(grp);
		// }
		// if (g3 != null && !hasColleague) {
		// ContactGroup grp = new ContactGroup();
		// grp.setGroupName(g3);
		// grps.add(grp);
		// }
		//
		// if (gOther != null && !gOther.isEmpty()) {
		// ContactGroup grp = new ContactGroup();
		// grp.setGroupName(gOther);
		// grps.add(grp);
		// }
		//
		// for (ContactGroup cg : theContact.getBooks()) {
		// if (!cg.getGroupName().equals(g1) && !cg.getGroupName().equals(g2)
		// && !cg.getGroupName().equals(g3)) {
		// String grpName = request
		// .getParameter(cg.getGroupName() + "Chk");
		// ContactGroup grp = new ContactGroup();
		// grp.setGroupName(grpName);
		// grps.add(grp);
		// }
		// }
		// theContact.setBooks(grps);

		try {

			dao.updateContact(theContact);
			if (!(theContact instanceof Entreprise)) {
				RequestDispatcher dispatcher = request
						.getRequestDispatcher("SearchContacts");
				dispatcher.forward(request, response);
			} else {
				RequestDispatcher dispatcher = request
						.getRequestDispatcher("SearchEnterprises");
				dispatcher.forward(request, response);
			}
		} catch (Exception e) {
			e.printStackTrace();
		}

	}
}
